package com.sbm.datasource.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "custom")
@AutoConfigureAfter(DefaultDataSourceConfig.class)
public class CustomDataSourceConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomDataSourceConfig.class);

    @Autowired
    private DefaultDataSourceConfig defaultConfig;

    private List<Map<String, Object>> datasource;

    private Map<String, DataSourceConfig> configs;

    public void initConfig() {
        if (this.configs == null) {
            try {
                this.configs = new HashMap<String, DataSourceConfig>();
                if(this.datasource==null)
                	return;
                for (Map<String, Object> map : this.datasource) {
                    for (Map.Entry<String, Object> entry : this.defaultConfig.getDataSourceConfig().getExtConfig()
                            .entrySet()) {
                        if (map.containsKey(entry.getKey()))
                            continue;
                        map.put(entry.getKey(), entry.getValue());
                    }
                    DataSourceConfig config = new DataSourceConfig(map);
                    this.configs.put(config.getName(), config);
                }
            } catch (Exception ex) {
                LOGGER.error("数据源：配置初始化失败——" + ex.getMessage());
                ex.printStackTrace();
            }
        }
    }

    public List<Map<String, Object>> getDatasource() {
        return datasource;
    }

    public void setDatasource(List<Map<String, Object>> datasource) {
        this.datasource = datasource;
    }

    public DataSourceConfig getDataSourceConfig(String name) {
        initConfig();
        if (this.configs != null && this.configs.containsKey(name))
            return this.configs.get(name);
        else
            return null;
    }

    public List<DataSourceConfig> getDataSourceConfigList() {
        initConfig();
        if (this.configs != null)
            return new ArrayList<DataSourceConfig>(this.configs.values());
        else
            return null;
    }
}
